<template>
  <view>
    <view :style="{ height: navBarHeight + 'px', background: '#fff' }">
      <image
          src="/static/left.png"
          mode="scaleToFill"
          class="icon"
          @click="goback"
        />
    </view>
    <alphaIndex-list
      :brands="brands"
      :groupedProducts="filteredProducts"
      :tabList="tabList"
      @brandChange="onBrandChange"
      @itemClick="onItemClick"
      @tabChange="onTabChange"
    />
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { request  } from '../utils/request'
import { onLoad } from '@dcloudio/uni-app'
// 所有品牌与数据
// const brands = ref(['品牌1', '品牌2', '品牌3'])
const brands = ref([])
const brandIndex = ref(0)
const allProducts = ref({})
const navBarHeight = ref(0)

// 模拟数据
// const allProducts = {
//   '品牌1': [
//     { letter: 'A', items: ['AP 战神2023款'] },
//     { letter: 'B', items: ['BP 战神2023款', 'BP 战神2023款'] },
//     { letter: 'C', items: ['CP 战神2023款', 'CP 战神2023款'] },
//   ],
//   '品牌2': [
//     { letter: 'B', items: ['BP 战神2023款', 'BP 战神2023款'] },
//     { letter: 'C', items: ['CP 战神2023款'] },
//   ],
//   '品牌3': [
//     { letter: 'A', items: ['AP 战神2023款'] },
//     { letter: 'B', items: ['BP 战神2023款', 'BP 战神2023款'] },
//     { letter: 'C', items: ['CP 战神2023款', 'CP 战神2023款'] },
//     { letter: 'A', items: ['AP 战神2023款'] },
//     { letter: 'B', items: ['BP 战神2023款', 'BP 战神2023款'] },
//     { letter: 'C', items: ['CP 战神2023款', 'CP 战神2023款'] },
//     { letter: 'A', items: ['AP 战神2023款'] },
//     { letter: 'B', items: ['BP 战神2023款', 'BP 战神2023款'] },
//     { letter: 'C', items: ['CP 战神2023款', 'CP 战神2023款'] },
//     { letter: 'A', items: ['AP 战神2023款'] },
//     { letter: 'B', items: ['BP 战神2023款', 'BP 战神2023款'] },
//     { letter: 'C', items: ['CP 战神2023款', 'CP 战神2023款'] },
//   ],
// }
const tabList = ref([
  // { name: '全部' },
  // { name: '其他' },
  // { name: '黑旋风系列' },
  // { name: '潮流男装' },
  // { name: '运动系列' },
  // { name: '春夏特供' },
  // 可继续添加更多项
])

const selectedBrand = ref('')
const selectedTab = ref(0)
const getNavHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  // 状态栏高度
  const statusBarHeight = systemInfo.statusBarHeight || 20
  // 胶囊按钮高度
  const capsuleHeight = menuButtonInfo.height || 32
  // 胶囊与状态栏的间距
  const topGap = menuButtonInfo.top - statusBarHeight
  // 整个自定义导航栏高度
  navBarHeight.value = (statusBarHeight + capsuleHeight + topGap * 2)
}
// 根据选中品牌筛选数据
const filteredProducts = computed(() => {
  return allProducts.value[selectedBrand.value] || []
})
const goback = () => {
    uni.switchTab({url: '/pages/index/index'})
  }
function buildAllProducts(brandList, productList) {
  const allProducts = {};

  for (const brand of brandList) {
    const brandName = brand.brandName;
    
    // 过滤出属于该品牌的产品
    const brandProducts = productList.filter(p => p.brandName === brandName);

    const letterMap = new Map();

    for (const product of brandProducts) {
      const letter = product.letter;
      const productName = product.productName;

      if (!letterMap.has(letter)) {
        letterMap.set(letter, []);
      }

      letterMap.get(letter).push(productName);
    }

    // 转换成数组结构并排序
    const letterGroups = Array.from(letterMap.entries())
      .map(([letter, items]) => ({ letter, items }))
      .sort((a, b) => a.letter.localeCompare(b.letter));

    allProducts[brandName] = letterGroups;
  }

  return allProducts;
}


const onBrandChange = (brand, i) => {
  selectedBrand.value = brand.brandName
  brandIndex.value = i
  if(brand.id == '') return;
  if(brandIndex.value) {
    selectedTab.value = 0
  }
  getSeriesList(brand.id)
  if(selectedTab.value) {
    getProjectList(brand.id, tabList.value[selectedTab.value].id)
  } else {
    getProjectList(brand.id, '')
  }
}

const onItemClick = (brand, item) => {
  const name = `${brand.brandName}/${item}`
  uni.navigateTo({
    url: `/pages/index/form2?name=${encodeURIComponent(name)}`
  })
}
// 获取系列列表
const getSeriesList = async (id) => {
  await request({
    url: '/series/list',
    method: 'GET',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: {
      brand_id: id
    }
  })
  .then(res => {
    if(res.code == 200) {
      console.log(333, res.data)
      res.data.unshift({ id: '' , serieName: '全部', brandId: '' })
      tabList.value = res.data
    } else {
      uni.showToast({
        title: res.data.message || '获取失败',
        icon: 'none'
      })
    }
  })
}
const onTabChange = (index) => {
  // 处理选中索引的逻辑
  selectedTab.value = index
  console.log('选中索引:', index)
  getProjectList(brands.value[brandIndex.value].id, tabList.value[index].id)
}
const getProjectList = async (brandId, seriesId) => {
  request({
    url: '/product/list',
    method: 'GET',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: {
      brand_id: brandId,
      series_id: seriesId
    }
  })
  .then(res => {
    if(res.code == 200){
      allProducts.value = buildAllProducts(brands.value, res.data)
    }
  })
}
// 获取品牌列表
const getBandList = async () => {
  await request({
    url: '/brand/list',
    method: 'GET',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
  })
  .then(async (res) => {
    if(res.code == 200) {
      res.data.push({ id: '', brandName: '其它品牌' })
      console.log(444, res.data)
      brands.value = res.data
      selectedBrand.value = res.data[0].brandName
    } else {
      uni.showToast({
        title: res.data.message || '获取失败',
        icon: 'none'
      })
    }
  })
}
onLoad((options) => {
  getNavHeight()
  getBandList()
})

</script>
<style scoped>
.icon{
  width: 40rpx;
  height: 40rpx;
  margin: 20rpx;
  position: absolute;
  top: 60rpx;
}
</style>
